import java.util.Arrays;

public class RouterProtocolPacket {
	
	
	public static final int ID_LENGTH = 1;
	public static final int DISTANCE_VECTOR_SIZE_LENGTH = 1;
	public static final int DISTANCE_VECTOR_MAX_LENGTH = Byte.MAX_VALUE;
	public static final int PACKET_LENGTH = ID_LENGTH+ DISTANCE_VECTOR_SIZE_LENGTH +DISTANCE_VECTOR_MAX_LENGTH*4;
	
	private byte idSender;
	private int[] distanceVector;

	public RouterProtocolPacket( byte idSender, int[] distanceVector) {
		this.setIdSender(idSender);
		this.setDistanceVector(distanceVector);
	}
	
	public RouterProtocolPacket( byte[] bytePacket ){
		this.setIdSender( bytePacket[0] );
		byte distanceVectorSize = bytePacket[1];
		int[] distanceVector = new int[distanceVectorSize];
		
		int k = 0;
		for (int i = 0; i < distanceVectorSize; i++) {
			byte[] dword = new byte[4];
			for (int j = 0; j < 4; j++) {
				dword[j] = bytePacket[2+(i*4)+j];
			}
			distanceVector[k++] = ByteIntegerUtil.dWordToInt(dword);
		}
		
		this.setDistanceVector(distanceVector);
	}
	
	public byte[] toByteArray(){


		byte[] bytePacket = new byte[PACKET_LENGTH];
		bytePacket[0] = this.getIdSender();
		bytePacket[1] = (byte)this.getDistanceVector().length;
		int k = 2;
		for (int i = 0; i < this.getDistanceVector().length; i++) {
			byte[] dword =  ByteIntegerUtil.intToDWord( this.getDistanceVector()[i] );
			bytePacket[k++] = dword[0];
			bytePacket[k++] = dword[1];
			bytePacket[k++] = dword[2];
			bytePacket[k++] = dword[3];
		}

		return bytePacket;
	}
	
	
	public int[] getDistanceVector() {
		return distanceVector;
	}

	public void setDistanceVector(int[] distanceVector) {
		assert distanceVector.length < Byte.MAX_VALUE;
		this.distanceVector = distanceVector;
	}

	public byte getIdSender() {
		return idSender;
	}

	public void setIdSender(byte idSender) {
		assert idSender >= 0 && idSender < Byte.MAX_VALUE;
		this.idSender = idSender;
	}
	
	public String toString(){
		return "[idSender="+this.getIdSender()+", distanceVector="+Arrays.toString(this.getDistanceVector())+"]";
	}
	
	public boolean equals( Object o ){
		if( !(o instanceof RouterProtocolPacket) ){
			return false;
		}
		RouterProtocolPacket other = (RouterProtocolPacket) o;
		
		return other.getIdSender() == this.getIdSender() && Arrays.equals( other.getDistanceVector(), this.getDistanceVector() ); 
	}

	


}
